<template>
  <div class="app-container">
    <el-container>
      <el-header>
        <h1>老年人病史管理系统</h1>
      </el-header>
      
      <el-main>
        <!-- 搜索和添加区域 -->
        <div class="operation-area">
          <el-input
            v-model="searchQuery"
            placeholder="请输入患者姓名或ID搜索"
            class="search-input"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加病史记录
          </el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="filteredRecords" style="width: 100%" border>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="age" label="年龄" width="80" />
          <el-table-column prop="diagnosis" label="诊断" />
          <el-table-column prop="date" label="就诊日期" width="180" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button-group>
                <el-button type="primary" @click="handleEdit(scope.row)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button type="danger" @click="handleDelete(scope.row)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加/编辑对话框 -->
        <el-dialog
          :title="dialogType === 'add' ? '添加病史记录' : '编辑病史记录'"
          v-model="dialogVisible"
          width="50%"
        >
          <el-form :model="form" label-width="100px">
            <el-form-item label="患者姓名">
              <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="年龄">
              <el-input-number v-model="form.age" :min="1" :max="120" />
            </el-form-item>
            <el-form-item label="诊断">
              <el-input v-model="form.diagnosis" type="textarea" />
            </el-form-item>
            <el-form-item label="就诊日期">
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:8000/api'

// 数据
const records = ref([
  {
    id: 1,
    name: '张三',
    age: 75,
    diagnosis: '高血压、糖尿病',
    date: '2023-01-15'
  },
  {
    id: 2,
    name: '李四',
    age: 68,
    diagnosis: '冠心病',
    date: '2023-02-20'
  }
])

// 搜索功能
const searchQuery = ref('')
const filteredRecords = computed(() => {
  if (!searchQuery.value) return records.value
  const query = searchQuery.value.toLowerCase()
  return records.value.filter(record => 
    record.name.toLowerCase().includes(query) || 
    record.id.toString().includes(query)
  )
})

// 表单数据
const dialogVisible = ref(false)
const dialogType = ref('add')
const form = ref({
  name: '',
  age: 65,
  diagnosis: '',
  date: ''
})

// 获取所有记录
const fetchRecords = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/records/`)
    records.value = response.data
  } catch (error) {
    ElMessage.error('获取记录失败')
    console.error('Error fetching records:', error)
  }
}

// 添加记录
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    age: 65,
    diagnosis: '',
    date: new Date()
  }
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    await axios.delete(`${API_BASE_URL}/records/${row.id}/`)
    const index = records.value.findIndex(item => item.id === row.id)
    records.value.splice(index, 1)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('Error deleting record:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (dialogType.value === 'add') {
      const response = await axios.post(`${API_BASE_URL}/records/`, form.value)
      records.value.push(response.data)
      ElMessage.success('添加成功')
    } else {
      await axios.put(`${API_BASE_URL}/records/${form.value.id}/`, form.value)
      const index = records.value.findIndex(item => item.id === form.value.id)
      records.value[index] = { ...form.value }
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '添加失败' : '修改失败')
    console.error('Error submitting form:', error)
  }
}

// 搜索处理
const handleSearch = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/records/`, {
      params: {
        search: searchQuery.value
      }
    })
    records.value = response.data
  } catch (error) {
    ElMessage.error('搜索失败')
    console.error('Error searching records:', error)
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: #fff;
  color: #333;
  line-height: 60px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
  margin-bottom: 20px;
}

.el-header h1 {
  margin: 0;
  font-size: 24px;
  text-align: center;
}

.operation-area {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
}

.search-input {
  width: 300px;
}

.el-main {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 